import React, { useState, useEffect } from 'react'
import './ServiceStatus.css'

export default function ServiceStatus() {
  const [services, setServices] = useState({
    backend: { status: 'checking', message: '检查中...' },
    chromadb: { status: 'checking', message: '检查中...' },
    ai: { status: 'checking', message: '检查中...' }
  })
  const [isExpanded, setIsExpanded] = useState(false)
  const [lastCheck, setLastCheck] = useState(null)

  // 检查服务健康状态
  async function checkHealth() {
    try {
      const response = await fetch('http://localhost:3001/api/health')
      const data = await response.json()
      
      setServices({
        backend: {
          status: 'healthy',
          message: '运行正常'
        },
        chromadb: {
          status: data.chromadb === 'connected' ? 'healthy' : 'error',
          message: data.chromadb === 'connected' ? '已连接' : '未连接'
        },
        ai: {
          status: data.ai_model === 'ready' ? 'healthy' : 'warning',
          message: data.ai_model === 'ready' ? '就绪' : data.ai_model || '未知'
        }
      })
      
      setLastCheck(new Date())
    } catch {
      setServices({
        backend: {
          status: 'error',
          message: '无法连接'
        },
        chromadb: {
          status: 'unknown',
          message: '未知'
        },
        ai: {
          status: 'unknown',
          message: '未知'
        }
      })
      setLastCheck(new Date())
    }
  }

  // 定期检查（每30秒）
  useEffect(() => {
    checkHealth()
    const interval = setInterval(checkHealth, 30000)
    return () => clearInterval(interval)
  }, [])

  // 计算整体状态
  const getOverallStatus = () => {
    const statuses = Object.values(services).map(s => s.status)
    if (statuses.includes('error')) return 'error'
    if (statuses.includes('warning')) return 'warning'
    if (statuses.every(s => s === 'healthy')) return 'healthy'
    return 'checking'
  }

  const overallStatus = getOverallStatus()

  // 状态图标和颜色
  const statusConfig = {
    healthy: { icon: '✅', color: '#10b981', label: '正常' },
    warning: { icon: '⚠️', color: '#f59e0b', label: '警告' },
    error: { icon: '❌', color: '#ef4444', label: '错误' },
    checking: { icon: '🔄', color: '#6b7280', label: '检查中' },
    unknown: { icon: '❓', color: '#9ca3af', label: '未知' }
  }

  const serviceNames = {
    backend: '后端服务',
    chromadb: '向量数据库',
    ai: 'AI 模型'
  }

  return (
    <div className={`service-status-widget ${isExpanded ? 'expanded' : ''}`}>
      <div 
        className="service-status-header"
        onClick={() => setIsExpanded(!isExpanded)}
      >
        <div className="status-indicator">
          <span className="status-icon">{statusConfig[overallStatus].icon}</span>
          <span className="status-label">系统状态</span>
          <span 
            className="status-badge"
            style={{ backgroundColor: statusConfig[overallStatus].color }}
          >
            {statusConfig[overallStatus].label}
          </span>
        </div>
        <button className="toggle-btn">
          {isExpanded ? '▼' : '▲'}
        </button>
      </div>

      {isExpanded && (
        <div className="service-status-content">
          <div className="services-list">
            {Object.entries(services).map(([key, service]) => (
              <div key={key} className="service-item">
                <div className="service-info">
                  <span className="service-icon">
                    {statusConfig[service.status].icon}
                  </span>
                  <div className="service-details">
                    <div className="service-name">{serviceNames[key]}</div>
                    <div className="service-message">{service.message}</div>
                  </div>
                </div>
                <div 
                  className="service-status-dot"
                  style={{ backgroundColor: statusConfig[service.status].color }}
                />
              </div>
            ))}
          </div>

          <div className="status-footer">
            <button 
              className="refresh-btn"
              onClick={(e) => {
                e.stopPropagation()
                checkHealth()
              }}
            >
              🔄 刷新
            </button>
            {lastCheck && (
              <div className="last-check">
                最后检查: {lastCheck.toLocaleTimeString('zh-CN')}
              </div>
            )}
          </div>

          {services.chromadb.status === 'error' && (
            <div className="status-alert">
              <div className="alert-icon">⚠️</div>
              <div className="alert-content">
                <div className="alert-title">ChromaDB 未连接</div>
                <div className="alert-message">
                  请确保 ChromaDB 服务已启动。系统将自动尝试重连...
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  )
}
